import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_base_widget/base/base_app.dart';
import 'package:flutter_base_widget/code2/second_page.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

//静态路由配置
void main() => runApp(BaseApp(homeWidget: Exam205HomePage()));

class Exam205HomePage extends StatefulWidget {
  @override
  State<Exam205HomePage> createState() => _Exam205HomePageState();
}
StreamController<String> streamController = StreamController.broadcast();
///代码清单 7-1-2
///lib/code7/code701_main_page.dart
class _Exam205HomePageState extends State<Exam205HomePage> {
  int _data = 0;

  @override
  Widget build(BuildContext context) {
    //Scaffold 用来搭建页面的主体结构
    return Scaffold(
      //页面的主内容区
      body: Center(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: () {
                _data++;
                ///第三步就是数据变化后
                ///赋值更新
                streamController.add("$_data");
              },
              child: const Text("+"),
            ),
            const SizedBox(width: 40),
            Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                BPage(),
                const SizedBox(height: 20),
                CPage(),
                const SizedBox(height: 20),
              ],
            )
          ],
        ),
      ),
    );
  }
}

///第三步设置监听
///代码清单 7-1-3
///lib/code7/code701_main_page.dart
class BPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return BPageState();
  }
}

///代码清单 7-4
class BPageState extends State {
  ///消息订单对象
  StreamSubscription? _streamSubscription;
  @override
  void initState() {
    super.initState();
    ///监听二
    _streamSubscription = streamController.stream.listen((event) {
      print("页面B接收到数据 $event");
    });
  }
  @override
  void dispose() {
    super.dispose();
    if(_streamSubscription!=null) {
      ///取消监听
      _streamSubscription?.cancel();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Text(
      '子视图中的内容',
      style: TextStyle(color: Colors.red),
    );
  }


}



class CPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<String>(
      ///绑定stream
      stream: streamController.stream,
      ///默认的数据
      initialData: "00:00:00",
      ///构建绑定数据的UI
      builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
        ///snapshot.data 就是传递的数据对象
        return Text(
          '当前值  ${snapshot.data} ',
          style: TextStyle(fontSize: 22, color: Colors.blue),
        );
      },
    );
  }
}
